package com.woniuxy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.woniuxy.service.ICodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yellow Docter
 * @date 2024-09-28
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Slf4j
@Service
public class ICodeServiceImpl implements ICodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String getCode(String phone) {
        String KEY = "code:" + phone;
        //RandomUtil hutool的工具类型
        // randomNumbers() 随机数字
        String code = RandomUtil.randomNumbers(4);

        ValueOperations ops = redisTemplate.opsForValue();

        //code 存储到Redis中 ttl 2min
        ops.set(KEY,code,2, TimeUnit.MINUTES);
        log.info("code 以存储到redis中");

        return code;
    }

    @Override
    public String login(String phone, String code) {
        String KEY = "code:" + phone;
        //01 通过phone 拿到 redis 中code
        ValueOperations ops = redisTemplate.opsForValue();
        Object redisStr = ops.get(KEY);
        //判断验证码
        if (Objects.isNull(redisStr) || !redisStr.toString().equals(code)){
            return "验证码过期...";
        }
        //02 判断code
        if (redisStr.toString().equals(code)){
            return " success...";
        }
        return "验证码输入错误.....";
    }

}
